package com.lagou.pojo;

import com.lagou.util.AbsoluteResourceUtil;
import com.lagou.util.HttpProtocolUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 封装Response
 */
public class Response {

    private OutputStream outputStream;

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 输出制定字符串,不包括响应头
     * @param output
     * @throws IOException
     */
    public void output(String output) throws IOException {
        outputStream.write(output.getBytes());
    }

    /**
     * 输出html资源
     * @param url
     */
    public void outputHtml(String url) throws IOException {
        //1.获取静态资源绝对路径
        String absoluteURL = AbsoluteResourceUtil.getAbsoluteUrl(url);

        //2.判断静态资源是否存在，存在则输出，否则输出404
        File file = new File(absoluteURL);
        if(file.exists() && file.isFile()){
            //3.读取静态资源
            AbsoluteResourceUtil.getResource(new FileInputStream(file), outputStream);
        } else {
            String response404 = HttpProtocolUtil.httpResponseHeader404();
            output(response404);
        }
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
}
